import { ApiResponse, SearchResult } from '@/types/data'
import { RootThunkAction, SearchAction } from '@/types/store'
import instance from '@/utils/request'
import { setHistory } from '@/utils/storage'

export const getSuggestionList = (value: string): RootThunkAction => {
  return async (dispatch) => {
    const res = await instance.get<ApiResponse<{ options: string[] }>>(
      '/suggestion',
      {
        params: {
          q: value,
        },
      }
    )
    // console.log(res)
    dispatch({
      type: 'search/getSuggestionList',
      payload: res.data.data.options,
    })
  }
}

export const getHistory = (keyword: string): RootThunkAction => {
  return async (dispatch, getState) => {
    let histories = getState().search.histories
    // 不允许重复
    histories = histories.filter((item) => item !== keyword)
    // 添加
    histories = [keyword, ...histories]
    if (histories.length > 10) {
      histories = histories.slice(0, 10)
    }
    dispatch({
      type: 'search/history',
      payload: histories,
    })
    setHistory(histories)
  }
}
export const clearSuggest = (): SearchAction => {
  return {
    type: 'search/clearSuggest',
  }
}

export const delHistory = (keyword: string): RootThunkAction => {
  return (dispatch, getState) => {
    let histories = getState().search.histories
    histories = histories.filter((item) => item !== keyword)
    dispatch({
      type: 'search/history',
      payload: histories,
    })
    setHistory(histories)
  }
}

export const clearHistory = (): SearchAction => {
  setHistory([])
  return {
    type: 'search/history',
    payload: [],
  }
}

export const getSearchResult = (
  q: string,
  page = 1,
  per_page = 10
): RootThunkAction => {
  return async (dispatch) => {
    const res = await instance.get<ApiResponse<SearchResult>>('/search', {
      params: {
        q,
        page,
        per_page,
      },
    })
    // console.log(res)

    dispatch({
      type: 'search/getSearchDetail',
      payload: res.data.data,
    })
  }
}
